package com.augurit.gzcgwsp.smartformCsdlwj.web;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.script.ScriptEngine;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.jbpm.api.JbpmException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.Struts2Utils;

import com.augurit.common.base.action.BaseAction;
import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.system.util.WebContextUtils;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.lhsp.service.IProcessInstanceService;
import com.augurit.gzcgwsp.lhsp.web.form.LhspSendItemNoticeForm;
import com.augurit.gzcgwsp.printDoc.service.IYwPrintDocService;
import com.augurit.gzcgwsp.printDoc.web.form.YwPrintDocForm;
import com.augurit.gzcgwsp.sendNotice.service.IYwMtbjlshInfoService;
import com.augurit.gzcgwsp.smartformCsdlwj.common.SmartDao;
import com.augurit.gzcgwsp.smartformCsdlwj.entity.YwSrCsdlwj;
import com.augurit.gzcgwsp.smartformCsdlwj.service.ISmartFormCsdlwjService;
import com.augurit.gzcgwsp.smartformCsdlwj.service.IYwCsdlwjService;
import com.augurit.gzcgwsp.smartformCsdlwj.web.form.CsdlwjForm;
import com.augurit.gzcgwsp.wfex.app.doc.IOaDocCodeServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfBusTemplateServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfTemplateAttachmentRefServiceEX;
import com.augurit.gzcgwsp.wfex.bi.web.form.WfTemplateAttachmentRefFormEX;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.gzcgwsp.wfex.common.util.WfUtilsEX;
import com.augurit.smartform.factory.ScriptEngineFactory;
import com.augurit.smartform.service.IFormExecuteService;
import com.augurit.smartform.service.IWfSupportService;
import com.augurit.smartform.test.TestService;
import com.augurit.wf.bi.convert.WfBusInstanceConvertor;
import com.augurit.wf.bi.service.IWfBusInstanceService;
import com.augurit.wf.bi.service.IWfBusTemplateService;
import com.augurit.wf.bi.web.form.WfActElemPrivDefForm;
import com.augurit.wf.bi.web.form.WfBusInstanceForm;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.bi.web.form.WfBusTemplateForm;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.entity.Jbpm4HistTask;
import com.augurit.wf.common.entity.WfBusInstance;
import com.augurit.wf.common.form.TraceRecord;
import com.augurit.wf.common.form.WfBusSaveResult;
import com.augurit.wf.common.service.IWfBusClientService;
import com.augurit.wf.common.service.IWfService;
import com.augurit.wf.common.tag.opinion.WfOpinionTag;
import com.augurit.wf.common.util.WfUtils;
import com.augurit.wf.common.web.WfBusClientExtAction;

@SuppressWarnings( { "serial", "unchecked" })
@Results( {
		@Result(name = CrudActionSupport.RELOAD, location = "smart-form-csdlwj.action", type = "redirect"),
		@Result(name = WfConstant.PRINT, location = WfConstant.PRINT_JSP),
		@Result(name ="gzxkz", location = "/gzcgwsp/dlwj/gzxkz.jsp"),
		@Result(name ="toUploadGzFile", location = "/gzcgwsp/dlwj/toUploadGzFile.jsp"),
		@Result(name = WfConstant.PRINT_DIR, location = WfConstant.PRINT_DIR_JSP),
		@Result(name = "yqData", location = "/gzcgwsp/dlwj/dlwj-yqb.jsp"),
		@Result(name = "sfb", location = "/gzcgwsp/dlwj/YwSr-sfb.jsp"),
		@Result(name = WfConstant.MAKE_DOCUMENT, location = "/gzcgwsp/wfex/client/common/make-rqjyxk-document.jsp"), 
		@Result(name = "quMakeDocument", location = "/gzcgwsp/wfex/client/common/qumake-noline-document.jsp"), 
		@Result(name = "toBjgzData", location = "/gzcgwsp/dlwj/dlwj-bjgz.jsp"),
		@Result(name = "preViewXkzs", location = "/gzcgwsp/dlwj/preViewXkzs.jsp"),
		@Result(name = "gzViewXkz", location = "/gzcgwsp/dlwj/gzViewXkz.jsp"),
		@Result(name = "tosimpleInput", location ="/gzcgwsp/dlwj/toDlwjSimple-input.jsp"),
		@Result(name = "listsimpleData", location ="/gzcgwsp/dlwj/listsimpleData.jsp"),
		@Result(name = "simpleInput", location ="/gzcgwsp/dlwj/dlwjSimple-input.jsp"),
		@Result(name = "toGcxx", location ="/gzcgwsp/ywcmn/lhsp/pageforsmartform/gcxx.jsp"),
		@Result(name = "toGcxmjbxx", location ="/gzcgwsp/ywcmn/lhsp/gcxmjbxx.jsp"),
		@Result(name = "toBlyj", location ="/gzcgwsp/ywcmn/lhsp/pageforsmartform/blyj.jsp"),
		@Result(name = "toBljd", location ="/gzcgwsp/ywcmn/lhsp/pageforsmartform/bljd.jsp"),
		@Result(name = "toSqcl", location ="/gzcgwsp/ywcmn/lhsp/pageforsmartform/sqcl.jsp"),
		@Result(name = "toGs", location = "/gzcgwsp/dlwj/dlwj-gs.jsp")
})
public class SmartFormCsdlwjAction extends WfBusClientExtAction {
	private final static Log log=LogFactory.getLog(SmartFormCsdlwjAction.class);
    @Autowired
    private IWfServiceEX wfServiceEX;   
	@Autowired
	private IWfBusTemplateService wfBusTemplateService;	
	@Autowired
	private TestService testService;
	@Autowired
	private IYwPrintDocService ywPrintDocService;	
	@Autowired
	private IWfSupportService wfSupportService;
	@Autowired
	private IFormExecuteService formExecuteService;
	@Autowired
	private IOaDocCodeServiceEX oaDocCodeServiceEX;
	@Autowired
	private IWfBusInstanceService wfBusInstanceService;
	@Autowired
	private IWfTemplateAttachmentRefServiceEX wfTemplateAttachmentRefServiceEX;
	@Autowired
	private SmartDao smartDao;
	@Autowired
	private IWfBusTemplateServiceEX wfBusTemplateServiceEX;
	@Autowired
	private ISmartFormCsdlwjService smartFormCsdlwjService;
	@Autowired
	private IYwMtbjlshInfoService ywMtbjlshInfoService;
	@Autowired
	private IYwCsdlwjService ywCsdlwjService;
	@Autowired
	private IWfService wfService;
    @Autowired
    private IProcessInstanceService processInstanceService;
	
	private Page<Map> pagemap = new Page<Map>(20);
	private Page<CsdlwjForm> page = new Page<CsdlwjForm>(20);
	private Map pageMap = new HashMap();

	private Long id;
	private CsdlwjForm form;
	
	/**
	 * 预览套打许可证
	 * @return
	 */
	public String preViewXkzs(){
	    String hjmc=getRequest().getParameter("hjmc");
	   
	    
	    String taskInstDbid = getRequest().getParameter("taskInstDbid");
	    if(StringUtils.isBlank(form.getCurYear())){
			 form.setCurYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
		}
	    if(StringUtils.isBlank(form.getZsbh())){
			
			 if(form.getTemplateCode().contains("qx")){
			    	if(StringUtils.isBlank(form.getZsbh())){
			    		 long seq = oaDocCodeServiceEX.getQuCurSeqAndAddSeq(form.getTemplateCode(),"xkz",form.getId(),this.getLoginUser());
			    		 String title=getLoginUser().getOrg().getOrgName().substring(0,1)+DateUtilsEX.getCurYear();
			    		 form.setCurSeq(title+"-"+getXkzSeq(seq));
			    		 form.setZsbh(title+"-"+getXkzSeq(seq));
			    	}
			    }else{
			    	 long seq = oaDocCodeServiceEX.getCurSeqAndAddSeq(form.getTemplateCode(),"xkz",form.getId(),false);
			    	if(StringUtils.isBlank(form.getZsbh())){
			    		String title="市"+DateUtilsEX.getCurYear();
			    		form.setZsbh(title+"-"+getXkzSeq(seq));
			    	}
			    }
		 }	
		
	    getRequest().setAttribute("hjmc", hjmc);
	    if(StringUtils.isBlank(form.getTemplateCode())){
	    	form.setTemplateCode("csdlwj");
	    }
	    getRequest().setAttribute("templateCode", form.getTemplateCode());
	    getRequest().setAttribute("taskInstDbid", taskInstDbid);
		if(form.getZsrq() == null){
			form.setZsrq(new Date());
		}
		
		return "preViewXkzs";
	}
	
	/**
	 * 预览套打许可证
	 * @return
	 */
	public String gzViewXkz(){
	    String hjmc=getRequest().getParameter("hjmc");
	    String taskInstDbid = getRequest().getParameter("taskInstDbid");
	    if(StringUtils.isBlank(form.getCurYear())){
			form.setCurYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
		}
	    if(StringUtils.isBlank(form.getZsbh())){
			 if(form.getTemplateCode().contains("qx")){
			    	if(StringUtils.isBlank(form.getZsbh())){
			    		 long seq = oaDocCodeServiceEX.getQuCurSeqAndAddSeq(form.getTemplateCode(),"xkz",form.getId(),this.getLoginUser());
			    		 String title=getLoginUser().getOrg().getOrgName().substring(0,1)+DateUtilsEX.getCurYear();
			    		 form.setCurSeq(title+"-"+getXkzSeq(seq));
			    		 form.setZsbh(title+"-"+getXkzSeq(seq));
			    	}
			    }else{
			    	 long seq = oaDocCodeServiceEX.getCurSeqAndAddSeq(form.getTemplateCode(),"xkz",form.getId(),false);
			    	if(StringUtils.isBlank(form.getZsbh())){
			    		String title="市"+DateUtilsEX.getCurYear();
			    		form.setZsbh(title+"-"+getXkzSeq(seq));
			    	}
			    }
	    }
	    
	    getRequest().setAttribute("hjmc", hjmc);
	    getRequest().setAttribute("templateCode", form.getTemplateCode());
	    getRequest().setAttribute("taskInstDbid", taskInstDbid);
	    try {
	    	YwPrintDocForm ywPrintDocForm = ywPrintDocService.getSltjFile(form.getTemplateCode(), "xkz",form.getId());
	    	String path = "";
	    	if(ywPrintDocForm != null){
	    		path = ywPrintDocForm.getPath();
	    	}
            getRequest().setAttribute("templateFilePath",path);
        } catch (Exception e) {
            log.error("查找许可文件出现错误");
        }
		if(form.getZsrq() == null){
			form.setZsrq(new Date());
		}

		return "gzViewXkz";
	}
	
	
	
	/**
	 * 显示简易录入的界面
	 * @return
	 * Mar 23, 2013
	 */
	public String simpleInput() {
		String templateCode=getRequest().getParameter("templateCode");
		WfBusTemplateForm template = wfBusTemplateService.getByTemplateCode(templateCode);		
		String wfDefId = WfUtils.convertToProcessDefinitionId(template.getWfDefKey(), template.getWfDefVersion());
		WfBusInstanceTaskForm instance=new WfBusInstanceTaskForm();
		instance.setActivityName(wfService.getStartTaskActivityName(wfDefId));
		//设置流程定义ID
		instance.setProcessDefId(wfDefId);
		//设置流程实体的版本
		instance.setVersion(template.getWfDefVersion());
		getRequest().setAttribute("instance", instance);
		getRequest().setAttribute("template", template);
		return "simpleInput";
	}
	
	/**
	 * 显示简易录入的列表
	 * @return
	 * Mar 23, 2013
	 */
	public String listsimpleData() {
		String area=this.getLoginUser().getOrg().getOrgName().substring(0,3);
		smartFormCsdlwjService.searchInputData(page, form,area);
		return "listsimpleData";
	}
	
	/**
	 * 到修改页面
	 * @return
	 */
	public String editSimpleInput(){
		Long taskDbId=smartFormCsdlwjService.getTaskDbIdById(form.getId());
		setTaskInstDbid(taskDbId);
		return "tosimpleInput";
	}
	
	/**
	 * 简易录入公示
	 * @return
	 * @throws Exception
	 */
	public String doSimpleGs() throws Exception{
		 if(form.getId()==null){
			 getResponse().getWriter().print("idnotExist");
		 }
		try {
			if(StringUtils.isBlank(form.getZsbh())){
				getResponse().getWriter().print("notcard");
				return null;
			}
			LoginUserForm uform=(LoginUserForm)this.getRequest().getSession().getAttribute("SES_LOGIN_USER");
			String returnStr = ywCsdlwjService.gs(form, uform);
			if(StringUtils.isBlank(returnStr)){
				getResponse().getWriter().print("success");
			}else{
				getResponse().getWriter().print(returnStr);
			}
		} catch (Exception e) {
			getResponse().getWriter().print("failure");
			e.printStackTrace();
		}
		return null;
		
	}
	
	/**
	 * 保存
	 * @return
	 */
	public String saveSimpleData() throws Exception{
		 form.setLarq(form.getTbrq());
		 form.setSarq(new Date());
		 
		 String acceptNo=getParameter("acceptNo");
		 form.setAcceptNo(acceptNo);	 
		 form.setSsq(getLoginUser().getOrg().getOrgName().substring(0,3));
		 form.setJbrxm(getLoginUserName());
		 form.setSqdw(form.getJsdw());
		 if(StringUtils.isNotBlank(form.getTemplateCode()) && "csdlwj".equals(form.getTemplateCode())){
			form.setCbyw("城市道路人行道及相关公共场地挖掘审批");
		 }else{
			form.setCbyw("区城市道路人行道及相关公共场地挖掘审批");
		}
		 form.setQu(getLoginUser().getOrg().getOrgName().substring(0,3));
		 WfBusInstanceTaskForm task = this.wfBusSave((IWfBusClientService)smartFormCsdlwjService, form, YwSrCsdlwj.class.getSimpleName());
		 if(task!=null){
			 this.smartFormCsdlwjService.updateJbpmState(form,task,acceptNo);
			 Long taskid=task.getTaskInstDbid();
	    	getResponse().getWriter().print(form.getId()+","+taskid);
	    }
		return null;
	}
	
	/**
	 * 窗口保存联合审批案件
	 * @return
	 */
	public String saveLhspData() throws Exception{
		String lhspId = super.getParameter("lhspId");		
		String ShenQingDanWeiR = super.getParameter("ShenQingDanWeiR");//申请单位（人）
		String ProContactName = super.getParameter("ProContactName");//联系人姓名
		String ProContactPhone = super.getParameter("ProContactPhone");//联系人手机
		String ProProjectName = super.getParameter("ProProjectName");//项目名称
		String ProConstructionUnitAddress = super.getParameter("ProConstructionUnitAddress");//项目地址
//		System.out.println("lhspId = "+lhspId);
//		System.out.println("ShenQingDanWeiR = "+ShenQingDanWeiR);
//		System.out.println("ProContactName = "+ProContactName);
//		System.out.println("ProContactPhone = "+ProContactPhone);
//		System.out.println("ProProjectName = "+ProProjectName);
//		System.out.println("ProConstructionUnitAddress = "+ProConstructionUnitAddress);
		form.setSarq(new Date());
		form.setTbrq(form.getSarq());
		form.setLarq(form.getTbrq());
		form.setJbrxm(ProContactName);
		form.setSqdw(ShenQingDanWeiR);
		form.setJsdw(ShenQingDanWeiR);
		form.setJsdwTel(ProContactPhone);
		form.setLxr(ProContactName);
		if(StringUtils.isNotBlank(form.getTemplateCode()) && "csdlwj".equals(form.getTemplateCode())){
			form.setCbyw("城市道路人行道及相关公共场地挖掘审批");
		}else{
			form.setCbyw("区城市道路人行道及相关公共场地挖掘审批");
		}
		if (StringUtils.isBlank(form.getAcceptNo())) {
        	//生成政务中心统一查询编号 开始
			Map<String,String> serialNoAndPasswordMap = null;
        	if("Y".equals(form.getSendNotice())){//网办，1
        		serialNoAndPasswordMap = ywMtbjlshInfoService.getSerialNoAndPassword("1");
        	}else{//大厅，0
        		serialNoAndPasswordMap = ywMtbjlshInfoService.getSerialNoAndPassword("0");
        	}
        	String serialNo = serialNoAndPasswordMap.get("serialNo");
        	String password = serialNoAndPasswordMap.get("password");
			form.setSerialNo(serialNo);
			form.setPassword(password);
			form.setAcceptNo(serialNo);
    		//生成政务中心统一查询编号 结束
        }
//		form.setQu(getLoginUser().getOrg().getOrgName().substring(0,3));
		WfBusInstanceTaskForm task = this.wfBusSave((IWfBusClientService)smartFormCsdlwjService, form, YwSrCsdlwj.class.getSimpleName());
		if(task!=null){//修改答复时间
			String procInstId = task.getProcInstId();
			processInstanceService.updateDfsjDate(form.getSarq(), procInstId);
			if(StringUtils.isNotBlank(lhspId)){
				form.setLhspId(Long.parseLong(lhspId));
				processInstanceService.changeIsLhsp(lhspId);
			}
	    }
		getResponse().getWriter().print("success");
		return null;
	}
	
	public String toGcxmjbxx(){
		return "toGcxmjbxx";
	}
	//到工程信息
	public String toGcxx(){
		return "toGcxx";
	}
	public String toBlyj(){
		return "toBlyj";
	}
	public String toBljd(){
		return "toBljd";
	}
	public String toSqcl(){
		return "toSqcl";
	}
	

	
	/**
	 * 简易录入
	 * @return
	 * Mar 23, 2013
	 */
	public String toSimpleInput() {
		String templateCode=getRequest().getParameter("templateCode");
		WfBusTemplateForm template = wfBusTemplateService.getByTemplateCode(templateCode);
		
		String wfDefId = WfUtils.convertToProcessDefinitionId(template.getWfDefKey(), template.getWfDefVersion());
		WfBusInstanceTaskForm instance=new WfBusInstanceTaskForm();
		instance.setActivityName(wfService.getStartTaskActivityName(wfDefId));
		
		//设置流程定义ID
		instance.setProcessDefId(wfDefId);
		
		//设置流程实体的版本
		instance.setVersion(template.getWfDefVersion());
		
		getRequest().setAttribute("instance", instance);
		getRequest().setAttribute("template", template);
		
		
		return "tosimpleInput";
	}
	
	/**
	 * 盖章前，检查是否已经制作了许可证
	 */
	public void checkXkzs() throws IOException{
		YwPrintDocForm ywPrintDocForm = ywPrintDocService.getSltjFile(form.getTemplateCode(), "xkz", form.getId());
		if(ywPrintDocForm != null){
			String path = ywPrintDocForm.getPath();
			if(StringUtils.isNotBlank(path)){
				getResponse().getWriter().print(path);
			}else{
				getResponse().getWriter().print("");
			}
		}
	}
	
	/**
	 * 经办人办理时候保存证书的内容
	 * @return
	 * @throws IOException 
	 */
	public String saveXkzs() throws IOException{
        String result="true";
        try {
        	ywCsdlwjService.save(form);
        	//保存时候生成编号 解决制文每次刷新生成新的编号问题
            oaDocCodeServiceEX.saveSeq(form.getTemplateCode(),"xkz", form.getId(),"false");
        } catch (Exception e) {
        	e.printStackTrace();
            result="false";
        }
        System.out.println("result = "+result);
        getResponse().getWriter().print(result);
	    return null;
	}

	/**
	 * 到收费环节
	 * @return
	 */
	public String toSfb()  throws Exception {
		
		return "sfb";
	}
	
	
	public String gzDoc() throws ParseException{
		cpbWldspUtil();
		form.setCbyw(form.getCbyw().replace("区县", "").replace("区", ""));
		form.setSarq(form.getTbrq());
		form.setDfsj(DateUtilsEX.dateFormate(wfServiceEX.getDfqx(form.getId(), 
				form.getTemplateCode()),"yyyy年MM月dd日"));
		form.setCpsj(DateUtilsEX.dateFormate(form.getTbrq(),"yyyy年MM月dd日"));
        if (form.getDfsj() == null) {
            Date dfsj = wfServiceEX.getDfqx(form.getId(), form.getTemplateCode());
            form.setDfsj(DateUtilsEX.dateFormate(dfsj,"yyyy年MM月dd日"));
        }
		String taskId=getRequest().getParameter("taskInstDbid");
		String activName="";
		if(StringUtils.isNotBlank(taskId)){
		  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
			activName=instance.getActivityName();
		    getRequest().setAttribute("activName", activName);
		}else{
			 getRequest().setAttribute("activName", "");
		}
		if(StringUtils.isNotBlank(form.getTemplateCode()) && form.getTemplateCode().contains("qx")){
			form.setShq("区");
		}else{
			form.setShq("市");
		}
		
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		if(form.getZsrq()!=null){
			form.setZsrqStr(sf.format(form.getZsrq()));
		}		
		if(form.getId() != null && form.getId() > 0){
			//加载收件通知书里面的附件
			 form = ywCsdlwjService.getSjtzsField(form);
			 String templateCode = getTemplateCode();
			 if(templateCode.indexOf("qx")>0){
				 form.setCbbm("市容科");
			 }
			 if (templateCode != null && templateCode.trim().length() > 0 && StringUtils.isNotBlank(form.getFileCode()) && "xkz".equals(form.getFileCode())) {
				 getRequest().setAttribute("isunified", false);//是否全委统一
				 form.setCurDate(DateUtilsEX.convertDate2Chinese(new Date()));
				 if(StringUtils.isBlank(form.getCurYear())){
					 form.setCurYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
				 }
				 if(StringUtils.isBlank(form.getZsbh())){
					 long seq = oaDocCodeServiceEX.getCurSeqAndAddSeq(templateCode,form.getFileCode(),form.getId(),false);
					 form.setCurSeq(getXkzSeq(seq));
					 form.setZsbh(form.getCurSeq());
				 }
			 }
			List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(form.getTemplateCode(), form.getFileCode(), form.getId());
        	if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0){
        		return "gzxkz";
    		}
    	}
		 Map variables= WfUtilsEX.buildMap(form, "yyyy年MM月dd日");
         ServletActionContext.getRequest().setAttribute(WfConstant.PRINT_BUFFER, variables);
         
         
         return "gzxkz";
	}
	
	
	public String printcz() throws Exception {
		cpbWldspUtil();
		form.setCbyw(form.getCbyw().replace("区县", "").replace("区", ""));
		form.setSarq(form.getTbrq());
		form.setDfsj(DateUtilsEX.dateFormate(wfServiceEX.getDfqx(form.getId(), 
				form.getTemplateCode()),"yyyy年MM月dd日"));
		form.setCpsj(DateUtilsEX.dateFormate(form.getTbrq(),"yyyy年MM月dd日"));
        if (form.getDfsj() == null) {
            Date dfsj = wfServiceEX.getDfqx(form.getId(), form.getTemplateCode());
            form.setDfsj(DateUtilsEX.dateFormate(dfsj,"yyyy年MM月dd日"));
        }
		String taskId=getRequest().getParameter("taskInstDbid");
		String activName="";
		if(StringUtils.isNotBlank(taskId)){
		  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
			activName=instance.getActivityName();
		    getRequest().setAttribute("activName", activName);
		}else{
			 getRequest().setAttribute("activName", "");
		}
		if(StringUtils.isNotBlank(form.getTemplateCode()) && form.getTemplateCode().contains("qx")){
			form.setShq("区");
			form.setSajg(this.getLoginUser().getOrg().getOrgName());
			form.setSajg3(this.getLoginUser().getOrg().getOrgName());
			form.setSajg2(this.getLoginUser().getOrg().getOrgName());
			form.setSajg4(this.getLoginUser().getOrg().getOrgName());
			form.setSajg5(this.getLoginUser().getOrg().getOrgName());
			form.setSajg6(this.getLoginUser().getOrg().getOrgName());
		}else{
			form.setShq("市");
		}
		LoginUserForm uform=(LoginUserForm)this.getRequest().getSession().getAttribute("SES_LOGIN_USER");
		String username=uform.getUser().getUserName();
		if(StringUtils.isNotBlank(form.getTemplateCode()) && form.getTemplateCode().contains("qx")){
    		form.setSajg(uform.getOrg().getOrgName());
    		form.setQu("("+uform.getOrg().getOrgName().substring(0, 1)+")");
		}else{
			form.setSajg("广州市城市管理委员会");
		}
    	
        form.setSajg2(form.getSajg());
        form.setSajg3(form.getSajg());
        form.setSajg4(form.getSajg());
        form.setSajg5(form.getSajg());
        form.setSajg6(form.getSajg());
        System.out.println("form.getSajg() = "+form.getSajg());
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		if(form.getZsrq()!=null){
			form.setZsrqStr(sf.format(form.getZsrq()));
		}		
		if(form.getId() != null && form.getId() > 0){
			//加载收件通知书里面的附件
			 form = ywCsdlwjService.getSjtzsField(form);
			 String templateCode = getTemplateCode();
			 if(templateCode.indexOf("qx")>0){
				 form.setCbbm("市容科");
			 }
			 form.setCurDate(DateUtilsEX.convertDate2Chinese(new Date()));
			 if (templateCode != null && templateCode.trim().length() > 0 && StringUtils.isNotBlank(form.getFileCode()) && "xkz".equals(form.getFileCode())) {
				 getRequest().setAttribute("isunified", false);//是否全委统一
				 if(StringUtils.isBlank(form.getCurYear())){
					 form.setCurYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
				 }
				 if(StringUtils.isBlank(form.getZsbh())){
					 long seq = oaDocCodeServiceEX.getCurSeqAndAddSeq(templateCode,form.getFileCode(),form.getId(),false);
					 form.setCurSeq(getXkzSeq(seq));
					 form.setZsbh(form.getCurSeq());
				 }
				 
			 }
			List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(form.getTemplateCode(), form.getFileCode(), form.getId());
        	if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0){
    			return WfConstant.PRINT_DIR;
    		}
    	}
        return WfUtilsEX.wfBusPrint(form,form.getId(),activName);
    }
	
	/**
	 * 盖章时获取许可证的文件路径
	 * @return
	 * @throws IOException 
	 */
	public String  getXkzFilePath() throws IOException{
		String ywId=getParameter("ywId");
		String templateId=getParameter("templateId");
		String templateCode=getParameter("templateCode");
		String fileCode=getParameter("fileCode");
		List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(templateCode, fileCode, Long.valueOf(ywId));
		if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0){
			YwPrintDocForm doc=ywPrintDocFormList.get(0);
			getResponse().getWriter().print(doc.getPath());
		}
		
		return null;
	}
	
	
	
	//打印  呈批表 委领导意见
	private void cpbWldspUtil(){
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String names = "'jbrsl' , 'jbrcs'";
		List<Jbpm4HistTask> list = wfServiceEX.getHandleCommentsByTaskInstDbidAndActivityNames(getTaskInstDbid(),names);
		StringBuffer wldspYj = new StringBuffer();
		if(list != null && list.size() > 0){
			for(int i=list.size()-1;i>=0;i--){
				if(StringUtils.isNotBlank(list.get(i).getHandleComments())){
					wldspYj.append(list.get(i).getHandleComments()).append("\n")
					.append("    ").append(list.get(i).getAssigneeName()).append("\n")
					.append(simpleDateFormat.format(list.get(i).getHandleCommentsTime())).append("\n");
					break;
				}
			}
		}
		form.setCpbJbryj(wldspYj.toString());
	}
	
	
	public String getXkzSeq(long seq){
		String seqStr = "";
		if(seq<10){
			seqStr = "00" + seq;
		}else if(seq >= 10 && seq < 100){
			seqStr = "0" + seq;
		}else{
			seqStr = "" + seq;
		}
		return seqStr;
	}
	
	/**
	 * 如果有延期保存延期天数
	 * @return
	 * @throws Exception
	 */
	public String insertOtherInfo() throws Exception {
		String days=this.getRequest().getParameter("yqts");
		String taskInstDbid=this.getRequest().getParameter("taskInstDbid");
		String acceptNo=this.getRequest().getParameter("acceptNo");
		Map map=this.getMapByRequest(this.getRequest());
		this.smartFormCsdlwjService.insertOtherInfo(map,taskInstDbid,acceptNo);
		this.getResponse().getWriter().print("success");
		return null;
	}
	
	/**
	 * 到补交告知页面
	 * @return
	 */
	public String toBjgz(){
		LoginUserForm form=(LoginUserForm)this.getRequest().getSession().getAttribute("SES_LOGIN_USER");
		String username=form.getUser().getUserName();
		this.getRequest().setAttribute("CurrUserName", username);
		setOpinions();
		if(this.getTemplateCode().contains("qx")){
			this.form.setBjsljtdd(form.getOrg().getOrgName());
		}
		return "toBjgzData";
	}
	
	/**
	 * 到公示页面
	 * @return
	 */
	public String toGs(){
		String zsbh = "";
		if(StringUtils.isNotBlank(form.getZsbh())){
			 if(form.getTemplateCode().contains("qx")){
			    	if(StringUtils.isBlank(form.getZsbh())){
			    		 long seq = oaDocCodeServiceEX.getQuCurSeqAndAddSeq(form.getTemplateCode(),"xkz",form.getId(),this.getLoginUser());
			    		 String title=getLoginUser().getOrg().getOrgName().substring(0,1)+DateUtilsEX.getCurYear();
			    		 form.setCurSeq(title+"-"+getXkzSeq(seq));
			    		 form.setZsbh(title+"-"+getXkzSeq(seq));
			    	}
			    }else{
			    	 long seq = oaDocCodeServiceEX.getCurSeqAndAddSeq(form.getTemplateCode(),"xkz",form.getId(),false);
			    	if(StringUtils.isBlank(form.getZsbh())){
			    		String title="市"+DateUtilsEX.getCurYear();
			    		form.setZsbh(title+"-"+getXkzSeq(seq));
			    	}
			    }
			
		}
		zsbh= form.getZsbh();
		this.getRequest().setAttribute("zsbh1", form.getZsbh());
		System.out.println("zsbh = "+zsbh);
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		if(form.getPzwjksrq() != null && form.getPzwjjsrq() != null){
			this.getRequest().setAttribute("sgqzrq", sf.format(form.getPzwjksrq()) + "至" + sf.format(form.getPzwjjsrq()));
		}
		
		return "toGs";
	}
	
	/**
	 * 公示
	 */
	public String gs() throws IOException{
		try {
			if(StringUtils.isBlank(form.getZsbh()) || StringUtils.isBlank(form.getCurYear())){
				getResponse().getWriter().print("许可证编号为空，请先制作许可证！");
				return null;
			}
			LoginUserForm uform=(LoginUserForm)this.getRequest().getSession().getAttribute("SES_LOGIN_USER");
			String returnStr = ywCsdlwjService.gs(form, uform);
			if(StringUtils.isBlank(returnStr)){
				getResponse().getWriter().print("success");
			}else{
				getResponse().getWriter().print(returnStr);
			}
		} catch (Exception e) {
			getResponse().getWriter().print("failure");
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 *获取延期的天数
	 * @return
	 * @throws Exception
	 */
	public String getYqDays() throws Exception {
		Map map = loadWfOpinionsByTaskInstDbid();

		String taskInstDbid=this.getRequest().getParameter("taskInstDbid");
		String acceptNo=this.getRequest().getParameter("acceptNo");
		String days=smartFormCsdlwjService.getYqDays(taskInstDbid,acceptNo);
		this.getResponse().getWriter().print(days);
		return null;
	}
	
	/**
	 * 到延期页面
	 * @return
	 */
	public String toYqData(){
		LoginUserForm uform=(LoginUserForm)this.getRequest().getSession().getAttribute("SES_LOGIN_USER");
		String username=uform.getUser().getUserName();
		this.getRequest().setAttribute("CurrUserName", username);
		String taskInstDbid=this.getRequest().getParameter("taskInstDbid");
		if(this.ywCsdlwjService.get(id)!=null){
			String acceptNo=this.ywCsdlwjService.get(id).getAcceptNo();
			String days=smartFormCsdlwjService.getYqDays(taskInstDbid,acceptNo);
			this.getRequest().setAttribute("yqts", days);
		}
		setOpinions();
		return "yqData";
	}
	/**
	 * 
	 * @return
	 * @throws IOException
	 */
	public String wfBusSave() throws IOException {

		this.executeWfSaveServer(); // 保存之前执行后端JS函数

		Long id = null;
		try {
			WfBusInstanceTaskForm task = wfSupportService
					.wfBusSave(getRequest());
			String entityKey = task.getMasterEntityKey();

			Map map = getRequest().getParameterMap();
			
			String ysl = BaseAction.getRequest().getParameter("SR_DLWJSQB_YSL");
			String[] obj=((String[])map.get("SR_DLWJSQB_JSDW"));
			String sqdw = ((String[]) map.get("SR_DLWJSQB_JSDW"))[0]; // 申请单位
			String sgdw = ((String[]) map.get("SR_DLWJSQB_SGDW"))[0]; // 施工单位
			//处理挖掘类别和收费表
			processingWjlb(entityKey);
			LoginUserForm user = (LoginUserForm)BaseAction.getRequest().getSession().getAttribute(WebContextUtils.SES_LOGIN_USER);
			String acceptNo = updateAcceptNoAndSumary(entityKey, sqdw, ysl,form,user); // 更新入受理号以及汇总字段

//			WfBusBaseEntity form = new WfBusBaseEntity();
			if (task != null && task.getMasterEntityKey() != null) {
				id = Long.valueOf(task.getMasterEntityKey());
			}
			form.setId(id);

			task.setMessage(acceptNo); // 设置受理编号

			if (ysl.equals("1")) { // 更新预受理状态
				ywCsdlwjService.changeYslState(id, 2l,null);
			}
			HttpServletRequest request = BaseAction.getRequest();
			//保存企业信息，用于企业信息重用
			Long qybh = ywCsdlwjService.saveEnterpriseInfo(request,id,sqdw,form.getTemplateCode());			
			if(qybh != null){
				form.setQybh(qybh.toString());
			}
			
			//保存施工单位信息，用于企业信息重用
			Long qybhTwo = ywCsdlwjService.saveYwComQyxxTwo(request, id, sgdw,form.getTemplateCode());
			if(qybhTwo != null){
				form.setQybhTwo(qybhTwo.toString());
			}
			
			WfUtils.renderWfBusSaveJson(task, form);

		} catch (Exception e) {
			WfBusSaveResult result = new WfBusSaveResult(true, "保存失败");
			Struts2Utils.renderJson(result);
			e.printStackTrace();
		}

		return null;
	}
	/**
	 * 处理挖掘类别
	 */
	public void processingWjlb(String id){
		
		Map maps = this.getMapByRequest(getRequest());
		StringBuilder sb = new StringBuilder();
		sb.append("Update SR_DLWJSQB_V4 t set ");
		String wjlb0 = (String)maps.get("SR_DLWJSQB_WJLB0"); // 挖掘类别0
		String wjlb1 = (String)maps.get("SR_DLWJSQB_WJLB1"); // 挖掘类别1
		String wjlb2 = (String)maps.get("SR_DLWJSQB_WJLB2"); // 挖掘类别2
		String wjlb3 = (String)maps.get("SR_DLWJSQB_WJLB3"); // 挖掘类别3
		String wjlb4 = (String)maps.get("SR_DLWJSQB_WJLB4"); // 挖掘类别4
		String wjlb5 = (String)maps.get("SR_DLWJSQB_WJLB5"); // 挖掘类别5
		String wjlb6 = (String)maps.get("SR_DLWJSQB_WJLB6"); // 挖掘类别6
		String wjlb7 = (String)maps.get("SR_DLWJSQB_WJLB7"); // 挖掘类别7
		String wjlb8 = (String)maps.get("SR_DLWJSQB_WJLB8"); // 挖掘类别8
		String fph = (String)maps.get("SR_DLWJSQB_fph"); // 
		String sfje = (String)maps.get("SR_DLWJSQB_sfje"); // 
		String sfbh = (String)maps.get("SR_DLWJSQB_sfbh"); // 
		if(StringUtils.isNotEmpty(wjlb0)){
			sb.append(" t.wjlb0="+wjlb0);
		}else{
			sb.append(" t.wjlb0=null");
		}
		
		if(StringUtils.isNotEmpty(wjlb1)){
			sb.append(" ,t.wjlb1="+wjlb1);
		}else{
			sb.append(" ,t.wjlb1=null");
		}
		
		if(StringUtils.isNotEmpty(wjlb2)){
			sb.append(" ,t.wjlb2="+wjlb2);
		}else{
			sb.append(" ,t.wjlb2=null");
		}
		
		if(StringUtils.isNotEmpty(wjlb3)){
			sb.append(" ,t.wjlb3="+wjlb3);
		}else{
			sb.append(" ,t.wjlb3=null");
		}
		
		if(StringUtils.isNotEmpty(wjlb4)){
			sb.append(" ,t.wjlb4="+wjlb4);
		}else{
			sb.append(" ,t.wjlb4=null");
		}
		
		if(StringUtils.isNotEmpty(wjlb5)){
			sb.append(" ,t.wjlb5="+wjlb5);
		}else{
			sb.append(" ,t.wjlb5=null");
		}
		
		if(StringUtils.isNotEmpty(wjlb6)){
			sb.append(" ,t.wjlb6="+wjlb6);
		}else{
			sb.append(" ,t.wjlb6=null");
		}
		
		if(StringUtils.isNotEmpty(wjlb7)){
			sb.append(" ,t.wjlb7="+wjlb7);
		}else{
			sb.append(" ,t.wjlb7=null");
		}
		
		if(StringUtils.isNotEmpty(wjlb8)){
			sb.append(" ,t.wjlb8="+wjlb8);
		}else{
			sb.append(" ,t.wjlb8=null");
		}
		if(StringUtils.isNotEmpty(fph)){
			sb.append(" ,t.fph='"+fph+"'");
		}else{
			sb.append(" ,t.fph=null");
		}
		if(StringUtils.isNotEmpty(sfje)){
			sb.append(" ,t.sfje="+sfje);
		}else{
			sb.append(" ,t.sfje=null");
		}
		if(StringUtils.isNotEmpty(sfbh)){
			sb.append(" ,t.sfbh='"+sfbh+"'");
		}else{
			sb.append(" ,t.sfbh=null");
		}
		sb.append(" where t.id="+id);
		smartDao.executeSql(sb.toString());
	}
	
	public String wfBusYslTuih() throws Exception {
    	try {
    		ywCsdlwjService.wfBusYslTuih(form, this.getLoginUser());
			WfBusSaveResult result = new WfBusSaveResult(true, null);
			result.setTask(new WfBusInstanceTaskForm());
			Struts2Utils.renderJson(result);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
        return null;
    }

	/**
	 * 制文
	 * 
	 * @return
	 * @throws Exception
	 */
	public String makeDocument() throws Exception {
		setOpinions();
		//加载收件通知书里面的附件
		 form = ywCsdlwjService.getSjtzsField(form);
		if (StringUtils.isNotBlank(form.getRedHeadFileId())) {
			String redHeadFilePath = wfBusTemplateServiceEX
					.getPrintTemplatePath(Long.parseLong(form
							.getRedHeadFileId()));
			form.setRedHeadFilePath(redHeadFilePath);
		}
		form.setQu("("+this.getLoginUser().getOrg().getOrgName().substring(0,1)+")");
		//加载收件通知书里面的附件
		 String isred=getRequest().getParameter("isred");
		 //如果要打印红头
		 if("yes".equals(isred) && !form.getTemplateCode().contains("qx")){
			 String redHeadFilePath = wfBusTemplateServiceEX.getRedFile(form.getTemplateCode());
		      form.setRedHeadFilePath(redHeadFilePath);
		 }else if("no".equals(isred)){
			 form.setRedHeadFilePath("");
		 }
		 System.out.println("form.getRedHeadFilePath() = "+form.getRedHeadFilePath());
		String templateCode = getTemplateCode();
		if (templateCode != null && templateCode.trim().length() > 0) {
			String printTemplatePath = wfBusTemplateServiceEX
					.getPrintTemplatePath(
							templateCode,
							WfTemplateAttachmentRefFormEX.ZHENGWEN_TEMPLATE_TYPE);
			form.setTemplatePath(printTemplatePath);
			if(StringUtils.isNotBlank(form.getTemplateCode()) && "csdlwj".equals(form.getTemplateCode())){
				form.setCbyw("城市道路人行道及相关公共场地挖掘审批");
			}else{
				form.setCbyw("区县城市道路人行道及相关公共场地挖掘审批");
			}
			
			form.setFzjg("广州市城市管理委员会");
			form.setTzlxr(getLoginUser().getUser().getUserName());
			WfTemplateAttachmentRefFormEX wfTemplateAttachmentRefFormEX = (WfTemplateAttachmentRefFormEX) wfTemplateAttachmentRefServiceEX
					.get(Long.parseLong(form.getZhengwenFileId()));
			String zhengwenPath = wfTemplateAttachmentRefFormEX.getFilePath()
					+ "/" + wfTemplateAttachmentRefFormEX.getFileRealName();
			form.setZhengwenPath(zhengwenPath);
			String slrq=smartFormCsdlwjService.getSlrq(form.getId(),wfTemplateAttachmentRefFormEX.getFileCode(),wfTemplateAttachmentRefFormEX.getId());
			if(StringUtils.isBlank(slrq))
				form.setSlrq(DateUtilsEX.convertDate2Chinese(new Date()));
			else
				form.setSlrq(slrq);
			form.setCurDate(DateUtilsEX.convertDate2Chinese(new Date()));
			if(StringUtils.isBlank(form.getCurYear())){
				 form.setCurYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
			}
			Long seq=0l;
			if(form.getTemplateCode().contains("qx")){
				 seq=oaDocCodeServiceEX.getQuCurSeqAndAddSeq(templateCode, wfTemplateAttachmentRefFormEX.getFileCode(),
	            		form.getId(),this.getLoginUser());
				
			}else{
				 seq=oaDocCodeServiceEX.getCurSeqAndAddSeq(templateCode,wfTemplateAttachmentRefFormEX.getFileCode(),
						 form.getId());
			}			
		    if(seq.intValue()<10){
	        	  form.setCurSeq("0"+String.valueOf(seq));
	        }else{
	        	  form.setCurSeq(String.valueOf(seq));
	        }
		    //form.setCurSeq(seq.toString());
			List list = smartFormCsdlwjService.getListById(form.getId());
			getRequest().setAttribute("isunified", false);//是否全委统一
			BaseAction.getRequest().setAttribute("seq", form.getCurSeq());
			WfUtilsEX.wfBusSmartFormPrint(form, list);
			BaseAction.getRequest().setAttribute("templateFilePath",zhengwenPath);
			BaseAction.getRequest().setAttribute("fileCode",
					wfTemplateAttachmentRefFormEX.getFileCode());
			BaseAction.getRequest().setAttribute("entityId", form.getId());
			BaseAction.getRequest().setAttribute("templateId",
					wfTemplateAttachmentRefFormEX.getId());
		}
		if(form.getTemplateCode().contains("qx")){
			return "quMakeDocument";
		}else{
			return WfConstant.MAKE_DOCUMENT;
		}
		
	}
	
	
	/**
	 * 页面保存之前执行业务逻辑
	 */
	private void executeWfSaveServer() {
		Map<String, Object> map = new HashMap<String, Object>();
		HttpServletRequest request = this.getRequest();
		this.setEngineMap(map);
		ScriptEngine scriptEngine = ScriptEngineFactory
				.getBindingScriptEngine(map);
		formExecuteService.executeWfSaveServer(scriptEngine, request);
	}

	/**
	 * 更新受理号 汇总字段
	 * 
	 * @param entityId
	 * @return
	 * @throws ParseException
	 */
	private String updateAcceptNoAndSumary(String entityId, String sqdw,String ysl,CsdlwjForm form,LoginUserForm user) {
		String acceptNo = "";

		// ====================判断受理号是否存在，更新受理号和汇总字段================
		if (entityId != null && entityId.trim().length() > 0) {
			String sjr = this.getLoginUser().getUser().getUserName();
			String isExist = "select ACCEPT_NO from SR_DLWJSQB_V4 where id = "
					+ entityId;
			List list = smartDao.getResultList(isExist);
			if (list != null) {
				Object obj = list.get(0);
				String s = (String) obj;
				if (s == null || s.trim().length() <= 0) {
					
					// ===================生成受理编号，更新受理编号开始========
					//生成政务中心统一查询编号 开始
					Map<String,String> serialNoAndPasswordMap = null;
		        	serialNoAndPasswordMap = ywMtbjlshInfoService.getSerialNoAndPassword("0");//大厅
		        	if(getTemplateCode().contains("qx")){
		        		//如果是区
		        		String area=this.getLoginUser().getOrg().getOrgName().substring(0,2);
		        		serialNoAndPasswordMap = ywMtbjlshInfoService.getQuSerialNoAndPassword("0",area);//大厅
			       }
		        	
		        	String serialNo = serialNoAndPasswordMap.get("serialNo");
		        	String password = serialNoAndPasswordMap.get("password");
		        	//生成政务中心统一查询编号 结束
		        	acceptNo = serialNo;
					String sql = "Update SR_DLWJSQB_V4 SET ACCEPT_NO ='"+ serialNo+ "',SERIAL_NO='"+ serialNo+"',PASSWORD='"+ password+ "' , SJR = '"+ sjr+ "' ";
					if(StringUtils.isNotBlank(form.getTemplateCode())){
						sql = sql + ",BRANCH = '"+form.getTemplateCode()+"' ";
					}
					sql = sql + "where ID = " + entityId;
					smartDao.executeSql(sql);
					// ==================生成受理编号，更新受理编号结束==========
					System.out.println("sjr = "+this.getLoginUser().getUser().getUserName());
					// 更新汇总
					WfBusInstance entity = wfBusInstanceService
							.getByMasterEntityAndKey("YwSrCsdlwj", entityId);
					entity.setBusMemo1(sqdw);
					entity.setBusMemo3(serialNo);
					if(StringUtils.isNotBlank(form.getTemplateCode()) && "csdlwj".equals(form.getTemplateCode())){
						entity.setBusMemo4("城市道路人行道及相关公共场地挖掘审批");
					}else{
						entity.setBusMemo4("区县城市道路人行道及相关公共场地挖掘审批");
					}
					entity.setBusDate2(new Date());
					WfBusInstanceForm wfForm = WfBusInstanceConvertor
							.convertVoToForm(entity);
					if(user != null && user.getOrg() != null && StringUtils.isNotBlank(user.getOrg().getOrgName())
							&& StringUtils.isNotBlank(form.getTemplateCode()) && form.getTemplateCode().contains("qx")){//区的业务，保存所属区到WfBusInstance表的busMemo2字段
						String orgName=user.getOrg().getOrgName();
						wfForm.setBusMemo2(orgName.substring(0,3));	
					}
					wfBusInstanceService.save(wfForm);

					form.setSjr(sjr);
				} else if ((s != null && s.trim().length() > 0) && ysl.equals("1")) { // 预受理状态下，更新汇总字段
					//设置收件人  开始
					String sql = "Update SR_DLWJSQB_V4 SET SJR = '"
						+ sjr
						+ "' where ID = " + entityId;
					smartDao.executeSql(sql);
					//设置收件人  结束
					acceptNo = s;
					WfBusInstance entity = wfBusInstanceService
							.getByMasterEntityAndKey("YwSrCsdlwj", entityId);
					entity.setBusMemo1(sqdw);
					entity.setBusMemo3(acceptNo);
					if(StringUtils.isNotBlank(form.getTemplateCode()) && "csdlwj".equals(form.getTemplateCode())){
						entity.setBusMemo4("城市道路人行道及相关公共场地挖掘审批");
					}else{
						entity.setBusMemo4("区县城市道路人行道及相关公共场地挖掘审批");
					}
					entity.setBusDate2(new Date());
					WfBusInstanceForm wfForm = WfBusInstanceConvertor.convertVoToForm(entity);
					if(user != null && user.getOrg() != null && StringUtils.isNotBlank(user.getOrg().getOrgName())
							&& StringUtils.isNotBlank(form.getTemplateCode()) && form.getTemplateCode().contains("qx")){//区的业务，保存所属区到WfBusInstance表的busMemo2字段
						String orgName=user.getOrg().getOrgName();
						wfForm.setBusMemo2(orgName.substring(0,3));	
					}
					wfBusInstanceService.save(wfForm);
					form.setSjr(sjr);
				} else {
					acceptNo = s;
				}
			}
		}
		System.out.println("+++++"+acceptNo);
		return acceptNo;
	}

	private void setEngineMap(Map map) {
		map.put("request", this.getRequest());
		map.put("response", this.getResponse());
		map.put("service", formExecuteService);
		map.put("page", pagemap);
		map.put("pageMap", pageMap);
		map.put("testService", testService);
	}
	
	/**
	 * 加载历史意见到制文中
	 */
	private void setOpinions(){
		String viewName=getRequest().getParameter("viewName");
		if(viewName == null){
			throw new JbpmException("视图参数不能为空，无法正确加载历史意见列表！");
		}
		
		Map<String, List<TraceRecord>> map = null;
		if(viewName.equals(WfActElemPrivDefForm.DB_ZB_VIEW)){
			map = loadWfOpinionsByTaskInstDbid();
		}
		else{
			map = loadWfOpinionsByProcInstDbid();
		}		StringBuilder opinionsStr = new StringBuilder("");
		if(map != null){
               Iterator it=map.entrySet().iterator();
               while(it.hasNext()){
            	   Map.Entry entrys=(Map.Entry)it.next();
            	   String key=(String) entrys.getKey();
            	   List<TraceRecord> traceRecords = (List<TraceRecord>) entrys.getValue();
            	   this.setOpinion(key, traceRecords);
             }
		}
		getRequest().setAttribute(WfOpinionTag.WF_OPINIONS, map);
	}
	
	/**
	 * 环节名称判断是哪个环节的意见
	 */
	private void setOpinion(String hjmc, List<TraceRecord> traceRecords){
		StringBuilder opinionsStr = new StringBuilder("");
		if(traceRecords != null && traceRecords.size() > 0){
				for(TraceRecord traceRecord:traceRecords){
					if(traceRecord.getHandleComments() != null && traceRecord.getHandleComments().trim().length() > 0){
						opinionsStr.append(traceRecord.getHandleComments());
					}
				}
		}
		if("jbrcs".equals(hjmc)){//
			form.setCsyj(opinionsStr.toString());
		}else if("czgldsh".equals(hjmc) || "cfgldsh".equals(hjmc)){
			String content=form.getFsyj()==null?"":form.getFsyj();
			if(StringUtils.isNotBlank(opinionsStr.toString())){
				content+=opinionsStr.toString()+"\n";
			}
			form.setFsyj(content);
		}else if("wfgldsh".equals(hjmc)){
			form.setSpyj(opinionsStr.toString());
		}
		
	}
	
	
	
	@Override
	public String delete() throws Exception {
		String ids=this.getRequest().getParameter("ids");
		try {
			smartFormCsdlwjService.deleteMore(ids);
			this.getResponse().getWriter().print("success");
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String list() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void prepareModel() throws Exception {
		if(id!=null){
			form =ywCsdlwjService.get(id);
		}else{
			form = new CsdlwjForm();
		}
		if(StringUtils.isNotBlank(form.getCbyw())){
			form.setCbyw(form.getCbyw().replace("区县", "").replace("区", ""));
		}
		if(form.getLhspId() != null){
        	LhspSendItemNoticeForm sendItemNoticeForm = processInstanceService.get(form.getLhspId());
        	this.getRequest().setAttribute("form", sendItemNoticeForm);
        }
		LoginUserForm uform=(LoginUserForm)this.getRequest().getSession().getAttribute("SES_LOGIN_USER");
		String username=uform.getUser().getUserName();
    	//补交告知原因
    	if(form.getBjgzyy()==null){
    		form.setBjgzyy(this.getOpinion("jbrsl"));
    	}
    	//补交告知时间
    	if(form.getBjgzsj()==null){
    		form.setBjgzsj(new Date());
    	}
    	//受理告知时间
    	if(form.getBjslsj()==null){
    		//form.setBjslsj(new Date());
    	}
    
    	//补交告知发出人
//    	if(form.getBjgzfcr()==null){
//    		form.setBjgzfcr(username);
//    	}
//        //补交告知受理人
//    	if(form.getSldwcbrxm()==null){
//    		form.setSldwcbrxm(username);
//    		
//    	}
    	//补交告知受理地点
    	if(form.getBjsljtdd()==null){
    		if(StringUtils.isNotBlank(form.getTemplateCode()) && form.getTemplateCode().contains("qx")){
    			form.setBjsljtdd(uform.getOrg().getOrgName());
    		}else{
    			form.setBjsljtdd("广州市城市管理委员会");
    		}    		
    	}
    	if(StringUtils.isNotBlank(form.getTemplateCode()) && form.getTemplateCode().contains("qx")){
    		form.setSajg(uform.getOrg().getOrgName());
    		form.setQu("("+uform.getOrg().getOrgName().substring(0, 1)+")");
		}else{
			form.setSajg("广州市城市管理委员会");
		}
    	
        form.setSajg2(form.getSajg());
        form.setSajg3(form.getSajg());
        form.setSajg4(form.getSajg());
        form.setSajg5(form.getSajg());
        form.setSajg6(form.getSajg());
	}
	
	/**
	 * 上传盖章文件
	 * @return
	 * @throws Exception 
	 */
	public String toUploadGzFile() throws Exception{
		String ajid=getParameter("ajid");
		String templateCode=getParameter("templateCode");
		String filename=getParameter("filename");
		String username=this.getLoginUserName();
		//filename=new String(filename.getBytes("iso-8859-1"),"gbk");
		getRequest().setAttribute("filename", filename);
		getRequest().setAttribute("ajid", ajid);
		getRequest().setAttribute("templateCode", templateCode);
		getRequest().setAttribute("username", username);
		return "toUploadGzFile";
	}


	
	 private  Map getMapByRequest(HttpServletRequest request) {
	        Map<String, String> map = new HashMap<String, String>();
	        Enumeration enu = request.getParameterNames();
	        while(enu.hasMoreElements()) {   
	            String paraName = (String)enu.nextElement();   
	            String paraValue = request.getParameter(paraName).trim(); 
	            //if(paraValue!=null && !"".equals(paraValue)){
	                map.put(paraName, paraValue);
	            //}           
	        }
	                
	        return map;
	    }
	 
	  
	@Override
	public String save() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	public Object getModel() {
		// TODO Auto-generated method stub
		return form;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}


	public Page<CsdlwjForm> getPage() {
		return page;
	}


	public void setPage(Page<CsdlwjForm> page) {
		this.page = page;
	}
}
